import { ref, computed } from 'vue'

/**
 * 智能布局管理组合式函数
 * @returns {Object} 布局管理方法和状态
 */
export function useSmartLayout() {
  const layoutGuides = ref([])
  const snapThreshold = ref(5)
  const gridSize = ref(20)
  const magneticAlignment = ref(true)

  /**
   * 自动对齐组件
   * @param {Array} components 所有组件
   * @param {Object} targetComponent 目标组件
   * @param {Object} newPosition 新位置
   * @returns {Object} 调整后的位置
   */
  const autoAlign = (components, targetComponent, newPosition) => {
    if (!magneticAlignment.value) return newPosition

    const alignedPosition = { ...newPosition }
    const guides = []

    // 获取其他组件的边界
    const otherComponents = components.filter(c => c.id !== targetComponent.id)
    
    for (const component of otherComponents) {
      const bounds = getComponentBounds(component)
      const targetBounds = {
        left: newPosition.x,
        top: newPosition.y,
        right: newPosition.x + targetComponent.size.width,
        bottom: newPosition.y + targetComponent.size.height,
        centerX: newPosition.x + targetComponent.size.width / 2,
        centerY: newPosition.y + targetComponent.size.height / 2
      }

      // 水平对齐检测
      const horizontalAlignments = [
        { type: 'left', target: targetBounds.left, reference: bounds.left },
        { type: 'center', target: targetBounds.centerX, reference: bounds.centerX },
        { type: 'right', target: targetBounds.right, reference: bounds.right }
      ]

      for (const alignment of horizontalAlignments) {
        const distance = Math.abs(alignment.target - alignment.reference)
        if (distance <= snapThreshold.value) {
          const offset = alignment.reference - alignment.target
          alignedPosition.x += offset
          
          guides.push({
            type: 'vertical',
            position: alignment.reference,
            start: Math.min(bounds.top, targetBounds.top),
            end: Math.max(bounds.bottom, targetBounds.bottom),
            alignment: alignment.type
          })
          break
        }
      }

      // 垂直对齐检测
      const verticalAlignments = [
        { type: 'top', target: targetBounds.top, reference: bounds.top },
        { type: 'middle', target: targetBounds.centerY, reference: bounds.centerY },
        { type: 'bottom', target: targetBounds.bottom, reference: bounds.bottom }
      ]

      for (const alignment of verticalAlignments) {
        const distance = Math.abs(alignment.target - alignment.reference)
        if (distance <= snapThreshold.value) {
          const offset = alignment.reference - alignment.target
          alignedPosition.y += offset
          
          guides.push({
            type: 'horizontal',
            position: alignment.reference,
            start: Math.min(bounds.left, targetBounds.left),
            end: Math.max(bounds.right, targetBounds.right),
            alignment: alignment.type
          })
          break
        }
      }
    }

    layoutGuides.value = guides
    return alignedPosition
  }

  /**
   * 智能分布组件
   * @param {Array} selectedComponents 选中的组件
   * @param {string} direction 分布方向 'horizontal' | 'vertical'
   */
  const distributeComponents = (selectedComponents, direction = 'horizontal') => {
    if (selectedComponents.length < 3) return

    const sortedComponents = [...selectedComponents].sort((a, b) => {
      if (direction === 'horizontal') {
        return a.position.x - b.position.x
      } else {
        return a.position.y - b.position.y
      }
    })

    const first = sortedComponents[0]
    const last = sortedComponents[sortedComponents.length - 1]
    
    let totalSpace
    let totalSize = 0

    if (direction === 'horizontal') {
      totalSpace = last.position.x - (first.position.x + first.size.width)
      totalSize = sortedComponents.slice(1, -1).reduce((sum, comp) => sum + comp.size.width, 0)
    } else {
      totalSpace = last.position.y - (first.position.y + first.size.height)
      totalSize = sortedComponents.slice(1, -1).reduce((sum, comp) => sum + comp.size.height, 0)
    }

    const spacing = (totalSpace - totalSize) / (sortedComponents.length - 1)
    
    let currentPosition = direction === 'horizontal' 
      ? first.position.x + first.size.width + spacing
      : first.position.y + first.size.height + spacing

    for (let i = 1; i < sortedComponents.length - 1; i++) {
      const component = sortedComponents[i]
      
      if (direction === 'horizontal') {
        component.position.x = currentPosition
        currentPosition += component.size.width + spacing
      } else {
        component.position.y = currentPosition
        currentPosition += component.size.height + spacing
      }
    }
  }

  /**
   * 对齐组件到指定边缘
   * @param {Array} selectedComponents 选中的组件
   * @param {string} alignment 对齐方式
   */
  const alignComponents = (selectedComponents, alignment) => {
    if (selectedComponents.length < 2) return

    const bounds = getSelectionBounds(selectedComponents)

    selectedComponents.forEach(component => {
      switch (alignment) {
        case 'left':
          component.position.x = bounds.left
          break
        case 'center':
          component.position.x = bounds.centerX - component.size.width / 2
          break
        case 'right':
          component.position.x = bounds.right - component.size.width
          break
        case 'top':
          component.position.y = bounds.top
          break
        case 'middle':
          component.position.y = bounds.centerY - component.size.height / 2
          break
        case 'bottom':
          component.position.y = bounds.bottom - component.size.height
          break
      }
    })
  }

  /**
   * 自动布局组件
   * @param {Array} components 组件列表
   * @param {string} layoutType 布局类型
   * @param {Object} options 布局选项
   */
  const autoLayout = (components, layoutType, options = {}) => {
    const {
      padding = 20,
      spacing = 16,
      columns = 3,
      containerWidth = 1200,
      containerHeight = 800
    } = options

    switch (layoutType) {
      case 'grid':
        layoutGrid(components, { columns, spacing, padding, containerWidth })
        break
      case 'flow':
        layoutFlow(components, { spacing, padding, containerWidth })
        break
      case 'stack':
        layoutStack(components, { spacing, padding })
        break
      case 'circle':
        layoutCircle(components, { containerWidth, containerHeight })
        break
    }
  }

  /**
   * 网格布局
   */
  const layoutGrid = (components, options) => {
    const { columns, spacing, padding } = options
    
    components.forEach((component, index) => {
      const row = Math.floor(index / columns)
      const col = index % columns
      
      component.position.x = padding + col * (component.size.width + spacing)
      component.position.y = padding + row * (component.size.height + spacing)
    })
  }

  /**
   * 流式布局
   */
  const layoutFlow = (components, options) => {
    const { spacing, padding, containerWidth } = options
    
    let currentX = padding
    let currentY = padding
    let rowHeight = 0

    components.forEach(component => {
      // 检查是否需要换行
      if (currentX + component.size.width > containerWidth - padding) {
        currentX = padding
        currentY += rowHeight + spacing
        rowHeight = 0
      }

      component.position.x = currentX
      component.position.y = currentY
      
      currentX += component.size.width + spacing
      rowHeight = Math.max(rowHeight, component.size.height)
    })
  }

  /**
   * 堆叠布局
   */
  const layoutStack = (components, options) => {
    const { spacing, padding } = options
    
    let currentY = padding

    components.forEach(component => {
      component.position.x = padding
      component.position.y = currentY
      currentY += component.size.height + spacing
    })
  }

  /**
   * 圆形布局
   */
  const layoutCircle = (components, options) => {
    const { containerWidth, containerHeight } = options
    
    const centerX = containerWidth / 2
    const centerY = containerHeight / 2
    const radius = Math.min(containerWidth, containerHeight) / 3
    
    components.forEach((component, index) => {
      const angle = (index / components.length) * 2 * Math.PI
      
      component.position.x = centerX + Math.cos(angle) * radius - component.size.width / 2
      component.position.y = centerY + Math.sin(angle) * radius - component.size.height / 2
    })
  }

  /**
   * 智能调整组件大小
   * @param {Array} selectedComponents 选中的组件
   * @param {string} sizeType 调整类型
   */
  const resizeComponents = (selectedComponents, sizeType) => {
    if (selectedComponents.length < 2) return

    const bounds = getSelectionBounds(selectedComponents)

    selectedComponents.forEach(component => {
      switch (sizeType) {
        case 'same-width':
          component.size.width = bounds.width
          break
        case 'same-height':
          component.size.height = bounds.height
          break
        case 'same-size':
          component.size.width = bounds.width
          component.size.height = bounds.height
          break
      }
    })
  }

  /**
   * 获取组件边界
   * @param {Object} component 组件
   * @returns {Object} 边界信息
   */
  const getComponentBounds = (component) => {
    return {
      left: component.position.x,
      top: component.position.y,
      right: component.position.x + component.size.width,
      bottom: component.position.y + component.size.height,
      centerX: component.position.x + component.size.width / 2,
      centerY: component.position.y + component.size.height / 2,
      width: component.size.width,
      height: component.size.height
    }
  }

  /**
   * 获取选择区域边界
   * @param {Array} components 组件列表
   * @returns {Object} 边界信息
   */
  const getSelectionBounds = (components) => {
    if (components.length === 0) {
      return { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0, centerX: 0, centerY: 0 }
    }

    const bounds = components.reduce((acc, component) => {
      const compBounds = getComponentBounds(component)
      return {
        left: Math.min(acc.left, compBounds.left),
        top: Math.min(acc.top, compBounds.top),
        right: Math.max(acc.right, compBounds.right),
        bottom: Math.max(acc.bottom, compBounds.bottom)
      }
    }, {
      left: Infinity,
      top: Infinity,
      right: -Infinity,
      bottom: -Infinity
    })

    return {
      ...bounds,
      width: bounds.right - bounds.left,
      height: bounds.bottom - bounds.top,
      centerX: bounds.left + (bounds.right - bounds.left) / 2,
      centerY: bounds.top + (bounds.bottom - bounds.top) / 2
    }
  }

  /**
   * 检测组件重叠
   * @param {Array} components 组件列表
   * @returns {Array} 重叠的组件对
   */
  const detectOverlaps = (components) => {
    const overlaps = []

    for (let i = 0; i < components.length; i++) {
      for (let j = i + 1; j < components.length; j++) {
        const comp1 = components[i]
        const comp2 = components[j]
        
        if (isOverlapping(comp1, comp2)) {
          overlaps.push([comp1, comp2])
        }
      }
    }

    return overlaps
  }

  /**
   * 检查两个组件是否重叠
   * @param {Object} comp1 组件1
   * @param {Object} comp2 组件2
   * @returns {boolean} 是否重叠
   */
  const isOverlapping = (comp1, comp2) => {
    const bounds1 = getComponentBounds(comp1)
    const bounds2 = getComponentBounds(comp2)

    return !(bounds1.right <= bounds2.left || 
             bounds1.left >= bounds2.right || 
             bounds1.bottom <= bounds2.top || 
             bounds1.top >= bounds2.bottom)
  }

  /**
   * 自动解决重叠
   * @param {Array} components 组件列表
   * @param {Object} options 选项
   */
  const resolveOverlaps = (components, options = {}) => {
    const { method = 'push', spacing = 10 } = options
    const overlaps = detectOverlaps(components)

    overlaps.forEach(([comp1, comp2]) => {
      if (method === 'push') {
        // 推开重叠的组件
        const bounds1 = getComponentBounds(comp1)
        const bounds2 = getComponentBounds(comp2)
        
        const overlapX = Math.min(bounds1.right, bounds2.right) - Math.max(bounds1.left, bounds2.left)
        const overlapY = Math.min(bounds1.bottom, bounds2.bottom) - Math.max(bounds1.top, bounds2.top)
        
        if (overlapX < overlapY) {
          // 水平分离
          if (bounds1.centerX < bounds2.centerX) {
            comp2.position.x = bounds1.right + spacing
          } else {
            comp1.position.x = bounds2.right + spacing
          }
        } else {
          // 垂直分离
          if (bounds1.centerY < bounds2.centerY) {
            comp2.position.y = bounds1.bottom + spacing
          } else {
            comp1.position.y = bounds2.bottom + spacing
          }
        }
      }
    })
  }

  /**
   * 清除布局引导线
   */
  const clearGuides = () => {
    layoutGuides.value = []
  }

  /**
   * 获取布局建议
   * @param {Array} components 组件列表
   * @returns {Array} 布局建议
   */
  const getLayoutSuggestions = (components) => {
    const suggestions = []
    
    // 检测可能的对齐
    const alignmentSuggestions = detectPotentialAlignments(components)
    suggestions.push(...alignmentSuggestions)
    
    // 检测可能的分布
    const distributionSuggestions = detectPotentialDistributions(components)
    suggestions.push(...distributionSuggestions)
    
    // 检测重叠问题
    const overlapSuggestions = detectOverlapIssues(components)
    suggestions.push(...overlapSuggestions)
    
    return suggestions
  }

  const detectPotentialAlignments = (components) => {
    const suggestions = []
    // 实现对齐检测逻辑
    return suggestions
  }

  const detectPotentialDistributions = (components) => {
    const suggestions = []
    // 实现分布检测逻辑
    return suggestions
  }

  const detectOverlapIssues = (components) => {
    const suggestions = []
    const overlaps = detectOverlaps(components)
    
    if (overlaps.length > 0) {
      suggestions.push({
        type: 'warning',
        message: `检测到 ${overlaps.length} 个组件重叠`,
        action: 'resolve-overlaps',
        data: overlaps
      })
    }
    
    return suggestions
  }

  return {
    // 状态
    layoutGuides,
    snapThreshold,
    gridSize,
    magneticAlignment,
    
    // 对齐方法
    autoAlign,
    alignComponents,
    distributeComponents,
    resizeComponents,
    
    // 布局方法
    autoLayout,
    layoutGrid,
    layoutFlow,
    layoutStack,
    layoutCircle,
    
    // 工具方法
    getComponentBounds,
    getSelectionBounds,
    detectOverlaps,
    resolveOverlaps,
    clearGuides,
    getLayoutSuggestions
  }
}



